<template>
  <div>
    <el-form ref="form" :model="searchDivision" label-width="80px">
      <el-form-item label="">
        机构名称：<el-input v-model="searchDivision.name" style="width: 300px;padding-right: 50px" placeholder="请根据机构名查询"></el-input>
        机构代码：<el-input v-model="searchDivision.divisionCode" style="width: 300px;padding-right: 50px" placeholder="请根据机构代码查询"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>

    <el-form ref="form" :model="tableData" label-width="80px" style="margin-top: 20px;margin-left: -45px" >
      <el-form-item>
        <el-button icon="el-icon-plus" size="small" @click="add">新增行政区划</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 96%;margin-left: 2%">
      <el-table-column label="序号" width="180" >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构名称  " width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构代码" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.divisionCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上级机构名称" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.divisionParentName }}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <el-dialog :title=this.title :visible.sync="dialogFormVisible">
      <el-form :model="sysrole">
        <el-form-item label="行政区划名称" :label-width="formLabelWidth">
          <el-input v-model="sysrole.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="行政区划代码" :label-width="formLabelWidth">
          <el-input v-model="sysrole.divisionCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="行政区划等级" :label-width="formLabelWidth">
          <el-input v-model="sysrole.divisionLevel" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="行政区划所属" :label-width="formLabelWidth">
          <el-input v-model="sysrole.divisionType" autocomplete="off"></el-input>
        </el-form-item>
          <el-col :span="24">
            <el-form-item label="经度" prop="kqLongitude">
              <el-input v-model="sysrole.longitude" placeholder="自动带出" clearable :style="{ width: '100%' }" >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="纬度" prop="kqLatitude">
              <el-input v-model="sysrole.latitude" placeholder="自动带出" clearable :style="{ width: '100%' }" >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="轮廓" prop="kqLatitude">
              <el-input v-model="sysrole.outline" placeholder="自动带出" clearable :style="{ width: '100%' }" id="outline">
              </el-input>
            </el-form-item>
          </el-col>


          <!-- 控制按钮组 -->
          <div class="map-button" id="container">
            <div ref="gaode_Map" id="gaode_Map" style="width: 100%; height: 70vh; border: 1px solid #ccc;">
            </div>
            <el-button @click="dialogFormVisible = false" >取 消</el-button>
            <el-button type="primary" @click="addPopulation">确 定</el-button>
          </div>
        </el-form>







    </el-dialog>


<!--    <el-dialog :title=this.title1 :visible.sync="dialogFormVisible2">-->

<!--      <el-form :model="updpwd">-->
<!--        <el-form ref="form" :model="updpwd" :rules="rules" label-width="100px">-->
<!--          <el-form-item label="密码" prop="upwd">-->
<!--            <el-input v-model="updpwd.upwd" autocomplete="off"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="确认密码" prop="confirmPwd1">-->
<!--            <el-input v-model="confirmPwd1" autocomplete="off"></el-input>-->
<!--          </el-form-item>-->
<!--        </el-form>-->

<!--        <el-button @click="dialogFormVisible2 = false">取 消</el-button>-->
<!--        <el-button type="primary" @click="updatepwd">确 定</el-button>-->




<!--      </el-form>-->


<!--    </el-dialog>-->



    <el-dialog :title=this.title1 :visible.sync="dialogFormVisible1">
      <el-form :model="upddivision">
        <el-form-item label="行政区划名称" :label-width="formLabelWidth">
          <el-input v-model="upddivision.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="行政区划代码" :label-width="formLabelWidth">
          <el-input v-model="upddivision.divisionCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="行政区划等级" :label-width="formLabelWidth">
          <el-input v-model="upddivision.divisionLevel" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="行政区划所属" :label-width="formLabelWidth">
          <el-input v-model="upddivision.divisionType" autocomplete="off"></el-input>
        </el-form-item>
        <el-col :span="24">
          <el-form-item label="经度" prop="kqLongitude">
            <el-input v-model="upddivision.longitude" placeholder="自动带出" clearable :style="{ width: '100%' }" >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="纬度" prop="kqLatitude">
            <el-input v-model="upddivision.latitude" placeholder="自动带出" clearable :style="{ width: '100%' }" >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="轮廓" prop="kqLatitude">
            <el-input v-model="upddivision.outline" placeholder="自动带出" clearable :style="{ width: '100%' }" id="outline">
            </el-input>
          </el-form-item>
        </el-col>


        <!-- 控制按钮组 -->
        <div class="map-button" id="container">
          <div ref="gaode_Map1" id="gaode_Map1" style="width: 100%; height: 70vh; border: 1px solid #ccc;">
          </div>
          <el-button @click="dialogFormVisible = false" >取 消</el-button>
          <el-button type="primary" @click="updatePopulation">确 定</el-button>
        </div>
      </el-form>


    </el-dialog>

  </div>
</template>

<script>




import {findDivisionList,addDivision,updateDivision,delDivision} from "@/api/community/division";
import AMapLoader from "@amap/amap-jsapi-loader";
import {map} from "core-js/internals/array-iteration";

window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "a97ace3a685329a45d528a00b082b51d",
};
export default {


  data() {
    //这里存放数据"

    return {
      drawingManager: null,
      isDrawingEnabled: false, // 控制绘制工具是否“启用”的标记

      isHave: false,
      longitude:'',
      latitude:'',
      dialogFormVisible: false,
      formLabelWidth: '120px',
      plots:{
        longitude: '',
        latitude: '',
        outline: [] // 用于保存点击位置的经纬度信息数组
      },
      division:[],
      showModal: false,
      map: null,
      map1: null,
      auto: null,
      placeSearch: null,
      markers: [],
      position: {},
      tableData:[],
      open: false,
      loading: false,
      // visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      rules: {},
      input: "",
      input1: "",
      uploadedCount: 0, // 用于跟踪上传的图片数量,
      searchDivision:{
        name:'',
        divisionCode:''
      },
      lnglat: [],
      sysrole:{
        longitude: '',
        latitude: '',
        outline: [] // 用于保存点击位置的经纬度信息数组
      },
      upddivision:{
        longitude: '',
        latitude: '',
        outline: [] // 用于保存点击位置的经纬度信息数组
      },
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      title:'新增',
      title1:'编辑',
      arr:{
        // name:''
      },
      orgList: [],
      aa:0,
      mouseTool:null,
      mouseTool1:null,
    };
  },
  //计算属性 类似于data概念",
  computed: {},
  //监控data中的数据变化",
  watch: {},
  //方法集合",

  methods: {
    initMap() {
      let centerLen = [116.397452, 39.90918];


      AMapLoader.load({
        key: "085f7d1a48acc9b9611b99096b0a0589",
        version: "2.0",
        plugins: ["AMap.DistrictSearch","AMap.Geocoder","AMap.AutoComplete", "AMap.PlaceSearch",
          'AMap.Scale','AMap.MouseTool']
      })
        .then((AMap) => {
          this.Amap = AMap;

          this.map = new AMap.Map("gaode_Map", {
            viewMode: "3D",
            zoom: 10, // 调整为适合显示整个区域的缩放级别
            center: centerLen,
            resizeEnable: true
          });
          this.map.on("click", this.clickMapHandler);
          // 初始化鼠标绘制工具
          var mouseTool = new AMap.MouseTool(this.map);

          mouseTool.polyline();

          // 监听绘制完成事件

          AMap.event.addListener(mouseTool,
            'draw',
            (e) => {
              if (e.obj.CLASS_NAME === 'AMap.Polyline') {
                // 处理绘制的多边形，可以将其保存或展示到地图上
                var polygon = new AMap.Polygon({
                  path: e.obj.getPath(),
                  strokeColor: "#FF0000",
                  strokeWeight: 2,
                  strokeOpacity: 0.8,
                  fillOpacity: 0.4,
                  fillColor: '#EE2200',
                  zIndex: 50,
                  map: this.map
                });

                // 获取顶点经纬度
                var path = e.obj.getPath();
                var vertices = path.map(point => `${point.getLng()},${point.getLat()}`);
                var verticesStr = vertices.join(';');
                alert(verticesStr)

                // 关闭绘制工具
                mouseTool.close();

                // 将顶点经纬度赋值给输入框
                var inputBox = document.getElementById('outline');
                // this.plots.outline= verticesStr;
                inputBox.value = verticesStr;
              }
            });

          // 如果需要处理地图点击事件，请确保此事件处理器已正确绑定

        })
        .catch((e) => {
          console.error(e);
        });
    },
    initupdMap() {
      let centerLen = [116.397452, 39.90918];


      AMapLoader.load({
        key: "085f7d1a48acc9b9611b99096b0a0589",
        version: "2.0",
        plugins: ["AMap.DistrictSearch","AMap.Geocoder","AMap.AutoComplete", "AMap.PlaceSearch",
          'AMap.Scale','AMap.MouseTool']
      })
        .then((AMap) => {
          this.Amap = AMap;

          this.map1 = new AMap.Map("gaode_Map1", {
            viewMode: "3D",
            zoom: 10, // 调整为适合显示整个区域的缩放级别
            center: centerLen,
            resizeEnable: true
          });
          this.map1.on("click", this.clickMapHandlerUpd);
          // 初始化鼠标绘制工具
          var mouseTool = new AMap.MouseTool1(this.map);

          mouseTool.polyline();

          // 监听绘制完成事件

          AMap.event.addListener(mouseTool,
            'draw',
            (e) => {
              if (e.obj.CLASS_NAME === 'AMap.Polyline') {
                // 处理绘制的多边形，可以将其保存或展示到地图上
                var polygon = new AMap.Polygon({
                  path: e.obj.getPath(),
                  strokeColor: "#FF0000",
                  strokeWeight: 2,
                  strokeOpacity: 0.8,
                  fillOpacity: 0.4,
                  fillColor: '#EE2200',
                  zIndex: 50,
                  map: this.map1
                });

                // 获取顶点经纬度
                var path = e.obj.getPath();
                var vertices = path.map1(point => `${point.getLng()},${point.getLat()}`);
                var verticesStr = vertices.join(';');
                alert(verticesStr)

                // 关闭绘制工具
                mouseTool.close();

                // 将顶点经纬度赋值给输入框
                var inputBox = document.getElementById('outline');
                // this.plots.outline= verticesStr;
                inputBox.value = verticesStr;
              }
            });

          // 如果需要处理地图点击事件，请确保此事件处理器已正确绑定

        })
        .catch((e) => {
          console.error(e);
        });
    },
    clickMapHandler(e) {
      this.sysrole.longitude = e.lnglat.getLng();
      this.sysrole.latitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      alert(this.lnglat);
      this.sysrole.outline.push(this.lnglat);
      this.setMarker(this.lnglat);
    },
    clickMapHandlerUpd(e) {
      this.upddivision.longitude = e.lnglat.getLng();
      this.upddivision.latitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      alert(this.lnglat);
      this.upddivision.outline.push(this.lnglat);
      this.setMarkerUpd(this.lnglat);
    },
    //  添加标记
    setMarker(lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    setMarkerUpd(lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map1);
      this.markers.push(marker);
    },
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
    // updstatue(val){
    //   updStatue(val.id).then(
    //     res => {
    //       this.$message.success("修改成功")
    //       this.list()
    //     }
    //   )
    // },
    //
    //
    //
    //
    // updatepwd(){
    //   updateUpwd(this.updpwd).then(
    //     res => {
    //       this.$message.success("修改成功");
    //       this.dialogFormVisible2=false
    //       this.list()
    //     }
    //   )
    // },
    // uppupwd(val){
    //   this.dialogFormVisible2=true
    // },
    //
    handleEdit(val){

      this.dialogFormVisible1=true
      this.initupdMap()
      this.upddivision=val
      this.aa=val.id;

    },
    updatePopulation(aa){
      updateDivision(this.upddivision).then(
        res => {
          this.$message.success("修改成功");
          this.dialogFormVisible1=false
          this.list()
        }
      )
    },
    //
    //
    //
    // handleDelete(val){
    //   delUser(val.id).then(
    //     res => {
    //       this.$message.success("删除成功")
    //       this.list()
    //     }
    //   )
    // },
    addPopulation(){
      addDivision(this.sysrole).then(
        res => {
          this.$message.success(res.msg)
          this.dialogFormVisible=false
          this.list()
        }
      )
    },
    list(){
      findDivisionList(this.searchDivision).then(res => {
        this.tableData = res.data;
        console.log(res);
      })

    },

    add(){
      this.dialogFormVisible=true
      this.initMap();
    },
    onSubmit(){
      this.list();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.list();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）",
  mounted() {
  },
  beforeCreate() {
  }, //生命周期 - 创建之前",
  beforeMount() {
  }, //生命周期 - 挂载之前",
  beforeUpdate() {
  }, //生命周期 - 更新之前",
  updated() {
  }, //生命周期 - 更新之后",
  beforeDestroy() {
  }, //生命周期 - 销毁之前",
  destroyed() {
  }, //生命周期 - 销毁完成",
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发",
};
</script>
<style scoped>

</style>
<style>
/* 如果需要，可以添加以下CSS到您的样式表中 */
.card-wrapper {
  /* 可以添加一些额外的样式来控制卡片的间距或布局 */
}

.custom-card .card-header {
  /* 根据需要自定义标题区域的样式 */
  padding: 10px; /* 根据实际情况调整 */
}

.custom-card .card-header .card-title {
  /* 小区名字和地址的容器样式 */
  display: flex;
  flex-direction: column; /* 使名字和地址垂直排列 */
}

.custom-card .card-header .card-image {
  /* 图片的容器样式，这里主要为了演示，实际上图片已经在HTML中直接设置了样式 */
}

.custom-card .card-body {
  /* 详细信息区域的样式 */
  padding: 10px; /* 根据实际情况调整 */

}
</style>
